import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get_it/get_it.dart';
import 'package:home_framework/api/dynamic_service.dart';
import 'package:home_framework/utils/dialogs.dart';
import 'api/upload_service.dart';
import 'dynamic_form.dart';
import 'interfaces/dynamic_listener.dart';
import 'models/dynamic_entity.dart';

class DynamicAdd extends StatefulWidget {
  DynamicAdd({Key key}) : super(key: key);

  @override
  _DynamicAddState createState() => _DynamicAddState();
}

class _DynamicAddState extends State<DynamicAdd> {
  Map<String, Map<String, Object>> _formData = {
    'title': {
      'value': '',
      'controller': TextEditingController(),
      'obsecure': false,
      'icon': Icons.title,
      'hintText': '请输入标题',
    },
    'content': {
      'value': '',
      'controller': TextEditingController(),
      'obsecure': false,
      'icon': Icons.content_paste,
      'hintText': '请输入内容',
    },
  };

  File _imageFile;

  @override
  void initState() {
    super.initState();
  }

  _handleTextFieldChanged(String formKey, String value) {
    this.setState(() {
      _formData[formKey]['value'] = value;
    });
  }

  _handleClear(String formKey) {
    this.setState(() {
      _formData[formKey]['value'] = '';
      (_formData[formKey]['controller'] as TextEditingController)?.clear();
    });
  }

  _handleImagePicked(File imageFile) {
    setState(() {
      _imageFile = imageFile;
    });
  }

  _handleSubmit() async {
    if ((_formData['title']['value'] as String).trim() == '') {
      Dialogs.showInfo(this.context, '标题不能为空');
      return;
    }

    if ((_formData['content']['value'] as String).trim() == '') {
      Dialogs.showInfo(this.context, '内容不能为空');
      return;
    }

    if (_imageFile == null) {
      Dialogs.showInfo(this.context, '图片不能为空');
      return;
    }
    EasyLoading.showInfo('请稍候...', maskType: EasyLoadingMaskType.black);
    String imageId;
    var imageResponse = await UploadService.uploadImage('image', _imageFile);
    if (imageResponse != null && imageResponse.statusCode == 200) {
      imageId = imageResponse.data['id'];
    }
    if (imageId == null) {
      Dialogs.showInfo(this.context, '图片上传失败');
      return;
    }

    Map<String, String> newFormData = {};
    _formData.forEach((key, value) {
      newFormData[key] = value['value'];
    });
    newFormData['imageUrl'] = imageId;
    var response = await DynamicService.post(newFormData);
    if (response != null && response.statusCode == 200) {
      Dialogs.showInfo(context, '添加成功');
      GetIt.instance
          .get<DynamicListener>()
          .dynamicAdded(DynamicEntity.fromJson(response.data));
      Navigator.of(context).pop();
    } else {
      Dialogs.showInfo(this.context,
          response?.statusMessage != null ? response.statusMessage : '添加失败');
    }

    EasyLoading.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('添加动态'),
        brightness: Brightness.dark,
      ),
      body: DynamicForm(
        _formData,
        _handleTextFieldChanged,
        _handleClear,
        '提交',
        _handleSubmit,
        _handleImagePicked,
        imageFile: _imageFile,
      ),
    );
  }
}
